using Cysharp.Threading.Tasks;
using DG.Tweening;
using UnityEngine;

namespace Light
{
    public class HeallthPanelController : MonoBehaviour
    {
        [SerializeField] private float curHealth = 100f;

        [SerializeField] private Vector2 targetSize;
        private RectTransform healthRed; //��ɫѪ��

        private RectTransform healthWhite; //��ɫѪ��


        private void Awake()
        {
            healthRed = transform.Find("TopBar").gameObject.GetComponent<RectTransform>();
            healthWhite = transform.Find("ButtomBar").gameObject.GetComponent<RectTransform>();
        }

        private void Start()
        {
            targetSize = healthRed.sizeDelta;
        }

        private void Update()
        {
            transform.LookAt(transform.position + Vector3.forward, Vector3.up);
        }

        /// <summary>
        ///     �Դ��ݽ������µ�Ѫ�����м���
        /// </summary>
        private float GetTrueWidth()
        {
            return curHealth * 5f / 100f;
        }

        /// <summary>
        ///     ˢ��Ѫ��
        /// </summary>
        public void Refresh(float val)
        {
            var diff = val - curHealth;
            curHealth = val;

            targetSize.x = GetTrueWidth();

            AdjustBarWidth(diff);
        }

        private async void AdjustBarWidth(float val)
        {
            var SuddenChangeBar = val >= 0 ? healthWhite : healthRed;
            var SlowChangeBar = val >= 0 ? healthRed : healthWhite;

            SuddenChangeBar.sizeDelta = targetSize;

            await UniTask.WaitForSeconds(0.1f);

            SlowChangeBar.DOSizeDelta(targetSize, 0.2f);
        }
    }
}